// Copyright (c) 2009 Daniel Waterworth.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.

#include "securitypass.h"
#include "securityexception.h"

#include <llvm/Instructions.h>
#include <llvm/Module.h>
#include <llvm/Constants.h>

#include <vector>

using std::vector;

char SecurityPass::ID = 0;

static bool check(LoadInst *i) {
  if (AllocaInst *a = dynamic_cast<AllocaInst*>(i->getPointerOperand())) {
    if (a->getType()->getDescription() == PointerType::get(i->getType(), 0)->getDescription())
      return true;
  }
  return false;
}

static bool check(StoreInst *i) {
  if (AllocaInst *a = dynamic_cast<AllocaInst*>(i->getPointerOperand())) {
    if (a->getType()->getDescription() == i->getOperand(1)->getType()->getDescription())
      return true;
  }
  return false;
}

bool SecurityPass::doInitialization(Module &M) {
  const Type *machine_size_t = IntegerType::get(sizeof(size_t)*8);
  
  if (M.getFunction("bounds_check"))
    throw security_exception;
  
  if (M.getFunction("alloc_check"))
    throw security_exception;
  
  vector<const Type*> args;
  args.push_back(PointerType::get(Type::Int8Ty, 0));
  args.push_back(machine_size_t);
  
  M.getOrInsertFunction("alloc_check", FunctionType::get(Type::VoidTy, args, 0));
  
  args.push_back(PointerType::get(Type::Int8Ty, 0));
  args.push_back(machine_size_t);
  
  M.getOrInsertFunction("bounds_check", FunctionType::get(Type::VoidTy, args, 0));
  
  if (M.getModuleInlineAsm() != "")
    throw security_exception;

  bounds_check_ = M.getFunction("bounds_check");
  alloc_check_ = M.getFunction("alloc_check");
  return true;
}

AllocaInst* IsStackAllocated(Value *val) {
  // traverse the instruction tree from val to find source of Pointer
  if (AllocaInst *a = dynamic_cast<AllocaInst*>(val))
    return a;
  if (GetElementPtrInst *i = dynamic_cast<GetElementPtrInst*>(val)) {
    return IsStackAllocated(i->getPointerOperand());
  }
  if (StoreInst *s = dynamic_cast<StoreInst*>(val)) {
    return IsStackAllocated(s->getPointerOperand());
  }
  if (LoadInst *l = dynamic_cast<LoadInst*>(val)) {
    return IsStackAllocated(l->getPointerOperand());
  }
  return NULL;
}

bool SecurityPass::runOnFunction(Function &F) {
  bool changed = false;
  
  /*
   On the security pass do the following:
   check referenced pointers (load and store ops)
  */
  // TODO: changeme
  const Type *machine_size_t = IntegerType::get(sizeof(size_t)*8);
  const PointerType *void_ptr = PointerType::get(Type::Int8Ty, 0);
  
  for (Function::iterator b = F.begin(), blockend = F.end(); b != blockend; ++b) {
    for (BasicBlock::iterator i = b->begin(), instrend = b->end(); i != instrend; ++i) {
      if (StoreInst *s = dynamic_cast<StoreInst*>(&*i)) {
        if (AllocaInst *alloca = IsStackAllocated(s)) {
          // the following code adds a bound_check funtion in front of store calls,
          // For a store instruction the first operand is the value and the second in the pointer.
          ConstantInt *element_size =
             ConstantInt::get(machine_size_t, target_data_->getTypeStoreSize(alloca->getType()->getElementType()));
          Value *args[4] = { new BitCastInst(alloca, void_ptr, "", &*i),
          BinaryOperator::Create(Instruction::Mul, element_size, new BitCastInst(alloca->getOperand(0), machine_size_t, "", &*i), "", &*i),
          new BitCastInst(s->getPointerOperand(), void_ptr, "", &*i),
          // TODO: change to getTypeAllocSize when upgraded to 2.6
          ConstantInt::get(machine_size_t, target_data_->getTypeStoreSize(s->getOperand(0)->getType())) };
          
          CallInst::Create(bounds_check_, args, args+4, "", &*i);
          changed = true;
        } else {
          // do an alloc_check instead
          Value *args[2] = { new BitCastInst(s->getPointerOperand(), void_ptr, "", &*i),
          ConstantInt::get(machine_size_t, target_data_->getTypeStoreSize(s->getOperand(0)->getType())) };
          
          CallInst::Create(alloc_check_, args, args+2, "", &*i);
          changed = true;
        }
      } else if (LoadInst *l = dynamic_cast<LoadInst*>(&*i)) {
        // For a load instruction the only operand is the ptr and
        // the return value (cast LoadInst to Value) is the value
        
      }
    }
  }
  
  return changed;
}

